package com.sky.controller.user;


import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@Slf4j
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类来查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId){
        log.info("查询分类下的菜品{}", categoryId);
        //查询菜品 通过缓存来优化
        String key = "dish_" + categoryId;
        List<DishVO> o = (List<DishVO>)redisTemplate.opsForValue().get(key);
        if(o !=null){ //假设有对应的缓存
            return Result.success(o);
        }
        Dish dish = new Dish();
        dish.setStatus(StatusConstant.ENABLE);
        dish.setCategoryId(categoryId);
        List<DishVO> dishVOS = dishService.listByDish(dish);
        redisTemplate.opsForValue().set(key,dishVOS);
        return Result.success(dishVOS);
    }
}
